package gee

import (
	"fmt"
	"net/http"
)

type Engine struct {
	router map[string]http.HandlerFunc
}

func New() *Engine {
	return &Engine{
		make(map[string]http.HandlerFunc),
	}
}

func (e Engine) AddRouter(method string, pattern string, handler http.HandlerFunc) {
	key := method + "-" + pattern
	value := handler
	e.router[key] = value
}

func (e Engine) GET(pattern string, handler http.HandlerFunc) {
	e.AddRouter("GET", pattern, handler)
}

func (e Engine) POST(pattern string, handler http.HandlerFunc) {
	e.AddRouter("POST", pattern, handler)
}

func (e Engine) Run(addr string) error {
	return http.ListenAndServe(addr, e)
}

func (e Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	method := req.Method
	path := req.URL.Path
	key := method + "-" + path

	if handler, ok := e.router[key]; ok {
		handler(w, req)
	} else {
		fmt.Fprintf(w, "404 NOT FOUND: %s\n", req.URL)
	}
}
